package edu.fmi.st.epf.types.team.common.handler;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.epf.uma.CustomCategory;

import edu.fmi.st.epf.types.projectmember.common.util.ProjectMemberHelper;
import edu.fmi.st.epf.types.team.common.TeamCommonActivator;
import edu.fmi.st.epf.types.team.common.util.TeamHelper;
import eu.tanov.epf.pv.service.types.handler.CustomTypeHandler;
import eu.tanov.epf.pv.service.types.service.CustomTypeHandlersService;
import eu.tanov.epf.pv.service.types.util.CustomCategoryCustomTypeReadOnlySettingDelegate;
import eu.tanov.epf.pv.service.types.util.CustomTypeHelper;

public class TeamCustomTypeHandler implements CustomTypeHandler<CustomCategory> {

	private static final String STRUCTURAL_FEATURE_NAME_PROJECT_MEMBERS = "project_members";

	public static final String TYPE_NAME = "Team";

	private final EClass teamEClass;
	private EReference projectMembers;

	public TeamCustomTypeHandler() {
		this.teamEClass = CustomTypeHelper.createType(TYPE_NAME);
	}

	/*
	 * based on http://www.ibm.com/developerworks/library/os-eclipse-dynamicemf/
	 */
	@Override
	public void registerType() {
		final CustomTypeHandler<CustomCategory> projectIterationTypeHandler = getProjectMemberTypeHandler();
		this.projectMembers = CustomTypeHelper
				.createStructuralFeatureList(
						teamEClass,
						STRUCTURAL_FEATURE_NAME_PROJECT_MEMBERS,
						projectIterationTypeHandler.getCustomType(),
						new CustomCategoryCustomTypeReadOnlySettingDelegate<CustomCategory>(
								projectIterationTypeHandler));

		teamEClass.getEStructuralFeatures().add(projectMembers);

		CustomTypeHelper.getExtendedUmaPackage().getEClassifiers()
				.add(teamEClass);
	}

	private CustomTypeHandler<CustomCategory> getProjectMemberTypeHandler() {
		final CustomTypeHandlersService service = TeamCommonActivator
				.getDefault().getService(CustomTypeHandlersService.class);
		final EClass projectMemberType = ProjectMemberHelper.getCustomType();

		return service.getHandlerForType(projectMemberType,
				CustomCategory.class);
	}

	@Override
	public EObject wrap(EObject object) {
		return CustomTypeHelper.copy(object, teamEClass);
	}

	@Override
	public boolean matches(EObject object) {
		return TeamHelper.isTeam(object);
	}

	@Override
	public EClass getCustomType() {
		return teamEClass;
	}

	@Override
	public Class<CustomCategory> getHolderType() {
		return CustomCategory.class;
	}

	@Override
	public String[] getCategoryPkgPath() {
		return TeamHelper.TEAMS_PATH;
	}

	@Override
	public boolean isReadyToRegisterType() {
		return ProjectMemberHelper.isRegistered();
	}

}
